import { getClassNameGenerator } from '@mao-fu/sun-ui-util';
import React, {
  type CSSProperties,
  type DetailedHTMLProps,
  type HTMLAttributes,
  type ReactNode,
} from 'react';
import './index.scss';

export type IconPresetSize =
  | 'inherit'
  | 'extra-small'
  | 'small'
  | 'default'
  | 'large'
  | 'extra-large';

export type IconSize = IconPresetSize | number;

export interface BaseIconProps
  extends Omit<
    DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>,
    'ref'
  > {
  /**
   * 扩展 className
   */
  className?: string;

  /**
   * 最外层扩展样式
   */
  style?: CSSProperties;
  /**
   * 子元素，一般是图标元素
   */
  children?: ReactNode;

  /**
   * 图标尺寸
   */
  size?: IconSize;

  /**
   * 是否持续旋转
   */
  spin?: boolean;

  /**
   * 旋转角度
   */
  rotate?: number;
}

const getClassName = getClassNameGenerator('base-icon');

export const BaseIcon: React.FC<BaseIconProps> = (props) => {
  const {
    className,
    style,
    children,
    size = 'inherit',
    spin = false,
    rotate = 0,
  } = props;

  const classes = getClassName('_', className, {
    // 内置尺寸
    [`size-${size}`]: typeof size !== 'number',
    // 持续旋转
    spin,
  });

  const outerStyle: CSSProperties = {};

  // 自定义尺寸
  if (typeof size === 'number') {
    outerStyle.fontSize = size;
  }

  // 旋转角度
  if (rotate) {
    outerStyle.transform = `rotate(${rotate}deg)`;
  }

  return (
    <span
      className={classes}
      style={{
        ...outerStyle,
        ...style,
      }}
    >
      {children}
    </span>
  );
};
